package com.rxyb.security.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rxyb.security.db.bean.SysUsercustom;
import com.rxyb.security.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author YJH
 * @version 1.0
 * @description
 * @date 2020/5/17  16:21
 */
@Slf4j
public class JWTAuthenticationFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(JwtConfig.HEADER_TOKEN_NAME);

        if (null != token && token.trim().length() > 0) {
            String tokenBody = null;
            try {
                tokenBody = JwtConfig.testJwt(token);
            } catch (Exception e) {
                log.error("转换异常" + e.getMessage());
                e.printStackTrace();

            }
            /* 从token中取出用户信息，放在上下文中 */
            if (tokenBody != null && tokenBody.trim().length() > 0) {
                JSONObject user = JSON.parseObject(tokenBody).getJSONObject("user");
                SysUsercustom sysUser = JsonUtils.jsonToPojo(JsonUtils.objectToJson(user), SysUsercustom.class);
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(sysUser, null, sysUser.getAuthorities()));
            } else {
                HttpServletResponse res = (HttpServletResponse) response;
                res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                res.getWriter().write("{\"code\": \"405\", \"msg\": \"token错误\"}");
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
